package com.tedu.mall.sso.service.iml;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.pojo.admin.model.Admin;
import cn.tedu.mall.common.pojo.sso.authentication.CsmallAuthenticationInfo;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.common.utils.JwtTokenUtils;
import com.tedu.mall.sso.mapper.AdminMapper;
import com.tedu.mall.sso.pojo.dto.AdminLoginDTO;
import com.tedu.mall.sso.service.AdminSSOService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminSSOServiceImpl implements AdminSSOService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    private StringRedisTemplate  stringRedisTemplate;






    @Override
    public String doLogin(AdminLoginDTO adminLoginDTO) {
        int adminCount = adminMapper.countByUsername(adminLoginDTO.getUsername());
        if (adminCount == 0) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "此用户名不存在");
        }
        Admin byUsername = adminMapper.findByUsername(adminLoginDTO.getUsername());
        System.out.println(byUsername.getPassword());
        System.out.println(adminLoginDTO.getPassword());
        System.out.println(adminLoginDTO.getPassword().equals(byUsername.getPassword()));
        if (!adminLoginDTO.getPassword().equals(byUsername.getPassword())) {
            throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST, "密码不匹配");
        }
        List<String> permissionsByUsername = adminMapper.findPermissionsByUsername(adminLoginDTO.getUsername());
        if (permissionsByUsername == null || permissionsByUsername.size() == 0) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "该用户没有权限");
        }
        CsmallAuthenticationInfo authenticationInfo = new CsmallAuthenticationInfo();
        authenticationInfo.setAuthorities(permissionsByUsername);
        authenticationInfo.setUsername(adminLoginDTO.getUsername());
        authenticationInfo.setUserType("admin");
        authenticationInfo.setId(byUsername.getId());

        String tocken = jwtTokenUtils.generateToken(authenticationInfo);


        return tocken;
    }

    @Override
    public void logout(String token) {
        String blackListKey="mall:sso:black:list:token:";
        SetOperations<String, String> operations = stringRedisTemplate.opsForSet();
        operations.add(blackListKey,token);

    }

    @Override
    public Admin findByUsername(String username) {
        Admin admin = adminMapper.findByUsername(username);
        return admin;
    }
}
